package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"hema-fresh/hemarpc/hemarpc"
	"hema-fresh/hemarpc/internal/svc"
	"hema-fresh/models/cache"
	"hema-fresh/models/mysql"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodListLogic {
	return &GoodListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 列表查询
func (l *GoodListLogic) GoodList(in *hemarpc.GoodListRequest) (*hemarpc.GoodListResponse, error) {
	//todo: add your logic here and delete this line
	var good mysql.Good
	var list []*hemarpc.GoodList
	key := fmt.Sprintf("goodsList_%s", in)
	result, _ := cache.Rdb.Get(l.ctx, key).Result()
	if result == "" {
		list, _ = good.GoodList(mysql.DB, in)
		marshal, _ := json.Marshal(list)
		cache.Rdb.Set(l.ctx, key, marshal, time.Minute*30)
	} else {
		json.Unmarshal([]byte(result), &good)
	}

	return &hemarpc.GoodListResponse{
		List: list,
	}, nil
}
